/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.service.fm.probe.ping;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import fr.jade.util.JadeException;

public class PongTask implements Runnable {

  protected DatagramSocket sock;
  protected byte[]         buf;
  protected DatagramPacket p;
  
  protected boolean started = true;
  
  public PongTask() throws JadeException{
    buf = new byte[8];
    p   = new DatagramPacket(buf, 8);
    try {
      sock = new DatagramSocket();
    } catch (SocketException e) {
      throw new JadeException("Can't create PongTask", e);
    }
  }
  
  public int getPort(){
    return sock.getLocalPort();
  }
  
  public void halt(){
    started = false;
  }
  
  public void run() {
    try {
      
      while (started) {
        pong(sock);
      }
    } catch (SocketException e) {
      System.err.println(e);
    } catch (Exception e) {
      System.err.println(e);
    }
  }

  protected void pong(DatagramSocket sock) throws IOException {
    sock.receive(p);
    InetAddress ip = p.getAddress();
    int port = p.getPort();
    p.setAddress(ip);
    p.setPort(port);
    sock.send(p);
  }

}
